using System;
using System.Collections.Generic;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.OracleClient;
using System.Configuration;

namespace uk.co.tonyditchfield.tort.database.providers
{
    internal static class DatabaseProvider
    {

        private static IDictionary<string, DbDetails> dBDetails = new Dictionary<string, DbDetails>();
        
        /// <summary>
        /// Provides a map of database connections and connection properties
        /// </summary>
        public static IDictionary<string, DbDetails> DBDetails
        {
            get 
            {
                // Only go and get details on first hit.
                if (dBDetails.Count == 0) { GetConnection(); }
                return DatabaseProvider.dBDetails; 
            }
        }

        public static bool IsReadOnly { get { return true; } }

        private static void GetConnection()
        {
            // Get the connectionStrings.
            ConnectionStringSettingsCollection connectionStrings =
                 ConfigurationManager.ConnectionStrings;

            // Get the collection enumerator.
            IEnumerator connectionStringsEnum =
                connectionStrings.GetEnumerator();

            // Loop through the collection and 
            // display the connectionStrings key, value pairs.
            int i = 0;
            while (connectionStringsEnum.MoveNext())
            {
                switch (connectionStrings[i].ProviderName.ToLower())
                {
                    case "system.data.sqlclient":
                        dBDetails.Add(connectionStrings[i].Name, new DbDetails(
                            connectionStrings[i].ConnectionString, connectionStrings[i].ProviderName.ToLower()));
                        break;
                    case "system.data.oracleclient":
                        dBDetails.Add(connectionStrings[i].Name, new DbDetails(
                            connectionStrings[i].ConnectionString, connectionStrings[i].ProviderName.ToLower()));
                        break;
                    default:
                        throw new exception.PersistenceException("Unsupported engine");
                }
                i++;
            }
        }
    }
}
